package com.yuebao.project.controller;

import com.yuebao.project.common.config.FileUploadProperties;
import com.yuebao.project.common.utils.DataResult;
import com.yuebao.project.service.HomeService;
import com.yuebao.project.service.HttpSessionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 *
 */
@RestController
@RequestMapping("/")
@Api(tags = "文件数据")
public class FileController {


    @Resource
    private FileUploadProperties fileUploadProperties;

    @GetMapping("/files/{folder}/{fileName:.+}*")
    @ApiOperation(value = "访问文件资源")
    public void getFileInfo(HttpServletRequest request, HttpServletResponse response,@PathVariable String folder,
                                  @PathVariable String fileName) throws Exception {

        // 设置编码
        response.setCharacterEncoding("UTF-8");


        String path = fileUploadProperties.getPath()+File.separator + folder + File.separator + fileName;
        File file = new File(path);
            if (!file.exists()) {
                path =ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images/404.png";
            }
         file = new File(path);
                try {
                    InputStream fis = new BufferedInputStream(new FileInputStream(file));
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    fis.close();
                    response.reset();
                    // 设置response的Header
                    response.addHeader("Content-Length", "" + file.length());
                    response.setContentType("image/png");
                    OutputStream toClient = new BufferedOutputStream(response.getOutputStream(), 888888);
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

    public static void main(String[] args) {

      String path =  ClassUtils.getDefaultClassLoader().getResource("").getPath();
        System.out.println(path);
    }

}
